import { Component, OnInit, OnDestroy } from '@angular/core';
import { WebSocketService } from 'app/ptpmc/comm/websocket-service';
import { ReportUrls } from 'app/ptpmc/comm/report.urls.conf';
import { LocalStorage } from 'app/ptpmc/localstorage/local.storage';
import { CommService } from 'app/ptpmc/comm/comm.service';
declare var h5_android;

@Component({
  selector: 'app-plane',
  templateUrl: './plane.component.html',
  styleUrls: ['./plane.component.scss']
})
export class PlaneComponent implements OnInit, OnDestroy {

  height;
  timeNow;
  production = [];
  production2 = [];
  production3 = [];
  listNow = [];
  listNow2 = [];
  listNow3 = [];
  listHistory = [];
  listHistory2 = [];
  listHistory3 = [];
  audioList = [];
  alarmMessage = [];

  timeInterval;

  connStatus = false;

  constructor(private wsService: WebSocketService, private ls: LocalStorage, private commServices: CommService) { }

  ngOnInit() {

    this.refreshHistory();

    // this.timeInterval = setInterval(() => {
    //   this.timeNow = this.formatDate(new Date(), 'yyyy-MM-dd hh:mm:ss');
    // }, 1000);

    const timeAudioInterval = setInterval(() => {
      if (this.audioList && this.audioList.length > 0) {
        const brower = navigator.userAgent;
        const currentAudio = this.audioList.shift();
        if (brower.indexOf('Android') !== -1) {
          h5_android.playMp3(currentAudio.value);
        } else {
          const a = document.createElement('audio');
          a.src = currentAudio.value;
          // console.log(currentAudio.value)
          a.play();
        }
      }
    }, 3000);

    setInterval(()=>{
      this.refreshHistory();
    },2000 * 60 )


    this.connWs();

  }


  connWs() {
    try {
      if (this.wsService && this.wsService.ws) { this.wsService.ws.close(); }
    } catch (e) {

    }
    const url = ReportUrls.BaseUrl.replace('http://', '');
    this.wsService.createObservableSocket(`ws://${url}/ws?uid=${this.ls.get('ptpmc_userId')}`)
      .subscribe(
        data => {
          this.connStatus = true;
          // console.log(data);
          try {
            const res = JSON.parse(data);
            if (res.key === 'exit') {
              // alert('当前账户在其它电脑登录！');
            } else if (res.key === 'play_wav_plane') {
              const wavUrl = ReportUrls.BaseUrl + res.value;
              res.value = wavUrl;
              this.audioList.push(res);
            } else if (res.key === 'prodState') {
              const value = JSON.parse(res.value);
              this.production = [];
              this.production2 = [];
              this.production3 = [];
              value.forEach(item => {
                const subArea = item.subArea;
                const equipment = item.equipment;
                const hours = item.hours;
                const unhours = item.unhours;
                const jph = item.jph;
                if (subArea == 'BL' || subArea == 'HL') {
                  this.production.push({ subArea: subArea, equipment: equipment, hours: hours,unhours: unhours, jph: jph });
                } else if (subArea == 'KL') {
                  this.production2.push({ subArea: subArea, equipment: equipment, hours: hours,unhours: unhours, jph: jph });
                } else {
                  this.production3.push({ subArea: subArea, equipment: equipment, hours: hours,unhours: unhours, jph: jph });
                }
              });
            } else if (res.key === 'fault') {
              const value = JSON.parse(res.value);
              this.listNow = [];
              this.listNow2 = [];
              this.listNow3 = [];
              value.forEach(item => {
                const subArea = item.subArea;
                const station = item.station;
                const duration = item.duration;
                const code = item.code;
                const faultWordDescription = item.faultWordDescription;

                if (subArea == 'CSBL1' || subArea == 'CSHL1') {
                  this.listNow.push(
                    { subArea: subArea, station: station, duration: duration, code: code, faultWordDescription: faultWordDescription }
                  );
                } else if (subArea == 'CSKL1') {
                  this.listNow2.push(
                    { subArea: subArea, station: station, duration: duration, code: code, faultWordDescription: faultWordDescription }
                  );
                } else {
                  this.listNow3.push(
                    { subArea: subArea, station: station, duration: duration, code: code, faultWordDescription: faultWordDescription }
                  );
                }
              });
            }
          } catch (e) {}
        },
        err => { console.log(err); },
        () => {
          console.log('连接断开');
          this.connStatus = false;
        }
      );
  }



  ngOnDestroy(): void {
    if (this.timeInterval) {
      clearInterval(this.timeInterval);
    }
  }
  formatDate(date: Date, fmt) {
    const o = {
      'M+': date.getMonth() + 1, // 月份
      'd+': date.getDate(), // 日
      'h+': date.getHours(), // 小时
      'm+': date.getMinutes(), // 分
      's+': date.getSeconds(), // 秒
      'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
      'S': date.getMilliseconds() // 毫秒
    };
    if (/(y+)/.test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
    };
    for (const k in o) {
      if (new RegExp('(' + k + ')').test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)));
      }
    }
    return fmt;
  }

  refreshHistory(){
    this.commServices
      .doGet('/tip/filter/list/current')
      .subscribe(model => {
        if (model.resultCode === 200) {
          this.listHistory = [];
          this.listHistory2 = [];
          this.listHistory3 = [];
          model.data.forEach(e => {
            const subArea = e.subArea;
            const duration = (Number.parseInt(e.duration) / 60).toFixed(0);
            if (subArea == 'CSBL1' || subArea == 'CSHL1') {
              this.listHistory.push(
                { subArea: subArea, station: e.station, duration: duration, shfitDay: e.startTime.split(" ")[1] });
            } else if (subArea == 'CSKL1') {
              this.listHistory2.push(
                { subArea: subArea, station: e.station, duration: duration, shfitDay: e.startTime.split(" ")[1] });
            } else {
              this.listHistory3.push(
                { subArea: subArea, station: e.station, duration: duration, shfitDay: e.startTime.split(" ")[1] });
            }
          });

        }
      });
      this.commServices
      .doGet('/tip/filter/list/msg')
      .subscribe(model => {
        if (model.resultCode === 200) {
          this.alarmMessage = model.data.map(e=>e.faultWordDescription);
        }
      });
  }

}
